//
//  AnimationExample.swift
//  SwiftCode
//
//  Created by yuhus on 2023/7/24.
//

import Foundation
import UIKit

class AnimationExample: ListViewController {
  override func getItemCount() -> Int {
    data.count
  }
  
  override func getItem(_ indexPath: IndexPath) -> Item {
    data[indexPath.row]
  }
  
  private lazy var data: [Item] = [
    .init(title: "UILabel", description: "scaleX 0.8", action: { [weak self] in self?.scale(x: 0.8, y: 0.8) }),
    .init(title: "UILabel", description: "reset", action: { [weak self] in self?.reset() }),
    .init(title: "UILabel.Layer", description: "anchorPoint: CGPoint(x: 0, y: 0)", action: { [weak self] in
      self?.setAnchorPoint(CGPoint(x: 0, y: 0))
    }),
    .init(title: "UILabel.Layer", description: "anchorPoint: CGPoint(x: 0.5, y: 0.5)", action: { [weak self] in
      self?.setAnchorPoint(CGPoint(x: 0.5, y: 0.5))
    }),
    .init(title: "UILabel.Layer", description: "scaleX 0.8", action: { [weak self] in self?.scaleLayer(x: 0.8, y: 0.8) }),
    .init(title: "UILabel.Layer", description: "reset", action: { [weak self] in self?.resetLayer() }),
  ]
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    [horizontalLine, verticallLine, titleLabel].forEach { view.addSubview($0) }
    horizontalLine.snp.makeConstraints { make in
      make.width.equalToSuperview()
      make.height.equalTo(1)
      make.center.equalToSuperview()
    }
    verticallLine.snp.makeConstraints { make in
      make.width.equalTo(1)
      make.height.equalToSuperview()
      make.center.equalToSuperview()
    }
    titleLabel.snp.makeConstraints { make in
      make.size.equalTo(100)
      make.center.equalToSuperview()
    }
  }
  
  private func setAnchorPoint(_ position: CGPoint) {
    titleLabel.layer.anchorPoint = position
  }
  
  private lazy var horizontalLine: UIView = {
    let view = UIView()
    view.backgroundColor = .black
    return view
  }()
  
  private lazy var verticallLine: UIView = {
    let view = UIView()
    view.backgroundColor = .black
    return view
  }()
  
  private lazy var titleLabel: UILabel = {
    let label = UILabel()
    label.text = "centerX"
    label.textAlignment = .center
    label.textColor = .red
    label.backgroundColor = .red.withAlphaComponent(0.1)
    return label
  }()
  
  private func scale(x: CGFloat, y: CGFloat) {
    UIView.animate(withDuration: 0.5) {
      self.titleLabel.transform = CGAffineTransform(scaleX: x, y: y)
    }
  }
  
  private func reset() {
    UIView.animate(withDuration: 0.5) {
      self.titleLabel.transform = CGAffineTransformIdentity
    }
  }
  
  private func scaleLayer(x: CGFloat, y: CGFloat) {
    UIView.animate(withDuration: 0.5) {
      self.titleLabel.layer.transform = CATransform3DScale(CATransform3DIdentity, x, y, 1)
    }
  }
  
  private func resetLayer() {
    UIView.animate(withDuration: 0.5) {
      self.titleLabel.layer.transform = CATransform3DIdentity
    }
  }
}
